<?php
namespace App\Http\Controllers\Admin;

use App\Models\Category;
use App\Http\Resources\Admin\Categories as CategoryCollection;
use Illuminate\Http\Request;

class CategoriesController extends Controller
{
    protected $_rules = [
        [
            'image' => 'string',
            'title' => 'required|string|max:20',
            'description' => 'string',
            'type' => 'integer',
        ],
    ];

    public function index(Request $request)
    {
        $orderBy = $this->getOrderByQuery([
            'id',
            'type',
        ]);
        $filters=$this->getFilterConditions(['type']);

        $result = Category::where($filters)
            ->orderByRaw($orderBy)
            ->orderByDesc('id')
            ->get();
        return new CategoryCollection($result);
    }

    public function store(Request $request)
    {
        $inputs = $this->validate($request, $this->_rules[0]);

        $record = Category::create($inputs);

        return $record;
    }

    public function update(Request $request, $id)
    {
        $record = Category::findOrFail($id);

        $inputs = $this->validate($request, $this->allowNullRules($this->_rules[0]));
        $inputs = $this->unsetEmptyFields($inputs, ['image']);

        $record->update($inputs);
        return $record;
    }

    public function destroy($id)
    {
        $record = Category::findOrFail($id);
        $result = Category::destroy($id);
        return [];
    }
}
